<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\logic\video\VideoLogic;
use app\common\model\Swiper;
use app\common\model\Video;
use app\common\model\VideoCategory;
use think\Db;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index(Video $videoModel, VideoCategory $videoCategoryModel, Swiper $swiperModel)
    {
        $categoryList = $videoCategoryModel->select();
        $this->view->assign('category', $categoryList);
        $selectedCategoryId = $this->request->get('selected_category_id');
        if (!$selectedCategoryId && $categoryList) {
            $selectedCategoryId = $categoryList[0]['id'];
        }
        $this->view->assign('selected_category_id', $selectedCategoryId);
        $this->view->assign('swiper_list', $swiperModel->select());
        //热门的 12条
        $this->view->assign('hot_video_list', $videoModel->where('category_id', $selectedCategoryId)->order('view_num', 'desc')->limit(12)->select());
        $this->view->assign('news_video_list', $videoModel->where('category_id', $selectedCategoryId)->order('id', 'desc')->limit(12)->select());
        return $this->view->fetch();
    }

    public function detail($id, $chapter_id = 0)
    {
        $videoModel = new Video();
        $detail = $videoModel->with([
            'chapter',
        ])->find($id);
        if (!$detail) {
            $this->error('视频不存在');
        }
        if ($chapter_id == 0 && $detail->chapter) {
            $chapter_id = $detail->chapter[0]['id'];
        }
        $error = $m3u8 = '';
        if (!$chapter_id) {
            $error = '无视频,请联系管理员';
        } else {
            $m3u8Url = VideoLogic::instance()->rpcM3u8ByChapterId($chapter_id);
            if ($m3u8Url === false) {
                $error = VideoLogic::instance()->getMessage();
            }
            $m3u8 = $m3u8Url;
        }
        $this->assign('error', $error);
        $this->assign('m3u8', $m3u8);
        $this->assign('current_chapter_id', $chapter_id);
        $this->view->assign('detail', $detail);
        return $this->view->fetch();
    }

    public function filter()
    {
        $data = $this->request->get();

        $videoCategoryModel = new VideoCategory();

        $this->view->assign('category_list', $videoCategoryModel->select());

        $videoModel = new Video();

        if ($categoryId = ($data['category_id'] ?? null)) {
            $videoModel = $videoModel->where('category_id', $categoryId);
        }

        if ($keyword = ($data['keyword'] ?? null)) {
            $videoModel = $videoModel->where('title', 'like', '%' . $keyword . '%');
        }
        $this->view->assign('list', $videoModel->order('id', 'desc')->paginate(15, false, [
            'query' => $data,
        ]));
        return $this->view->assign('request', $data)->fetch();
    }
}
